﻿using System.Workflow.Activities;
using System.Workflow.Runtime;
using Bookvar.ServiceModel;
using Bookvar.UpdateProcessWorkflow;
using System.Diagnostics.CodeAnalysis;

namespace Bookvar
{
	[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
	public class BookvarUpdateService : IUpdateService
	{
		private WorkflowRuntime runtime;
		private WorkflowInstance instance;

		public BookvarUpdateService( WorkflowRuntime runtime )
		{
			this.runtime = runtime;
		}

		#region IUpdateService Members

		public void StartCheckForUpdates()
		{
			if ( runtime == null )
			{
				runtime = new WorkflowRuntime();
//			if(!runtime.IsStarted)
//			{
				runtime.StartRuntime();
			}
//			}
			ExternalDataExchangeService dataService = runtime.GetService( typeof(ExternalDataExchangeService)) as ExternalDataExchangeService;
			if(dataService == null)
			{
				dataService = new ExternalDataExchangeService();
				runtime.AddService(dataService);	
			}
			UpdateProcessCommunicationService service = dataService.GetService(typeof(IUpdateProcessCommunicationService)) as UpdateProcessCommunicationService;
			if(service != null)
			{
				dataService.RemoveService( service );
			}
			
			service = new BookvarUpdateProcessCommunicationService();
			dataService.AddService( service );

			instance = runtime.CreateWorkflow( typeof ( UpdateProcess ) );
			instance.Start();
			service.InstanceId = instance.InstanceId;
			service.Instance = instance;
		}

		#endregion
	}
}